/**
 * 控件层: 负责管理显示的控件
 * @namespace Note.WidgetLayer
 *
 * WidgetLayer类继承自抽象接口
 * interface Layer{
 * 		void load(data);
 * 		array save();
 * 		void clear();
 * }
 * 
 * 构造函数
 * 
 * @constructor WidgetLayer
 * @author JunEnstein 2017-05-19
 * @param  string parent 父元素对象
 */
Note.WidgetLayer = function(parent){
	/**
	 * 父元素对象
	 * @type Object
	 */
	this._parent = parent;
	/**
	 * 控件序列
	 * @type {Array}
	 */
	this._widgets = [];
};

/**
 * 通过数据还原控件
 * @method load
 * @author JunEnstein 2017-05-19
 * @param  {Array} widgets 多个控件的数据
 */
Note.WidgetLayer.prototype.load = function(widgets){
	for(var i = 0; i < widgets.length; i++){
		this.append(new Note.WidgetFactory(widgets[i]));
	}
};

/**
 * 保存控件层的数据
 * @method save
 * @author JunEnstein 2017-05-19
 * @return {Array} 控件数据
 */
Note.WidgetLayer.prototype.save = function(){
	var data = [];
	for(var i = 0; i < this._widgets.length; i++){
		if(this._widgets[i]._name == 'Label'){
			data.push(this._widgets[i].save());
		}
	}
	return data;
};

/**
 * 清空控件层
 * @method clear
 * @author JunEnstein 2017-05-19
 */
Note.WidgetLayer.prototype.clear = function(){
	var widges = this._widgets;
	for(var widget in widgets){
		this.remove(widget);
	}
};

/**
 * 向控件层中追加一个控件
 * @method append
 * @author JunEnstein 2017-05-19
 * @param  {Widget} widget 控件对象
 */
Note.WidgetLayer.prototype.append = function(widget){
	var labels_count = 0;
	for(var i = 0; i < this._widgets.length; i++){
		if(this._widgets[i]._name = 'Label') labels_count++;
	}
	if(widget._name == 'Label'){
		widget.setId(labels_count+1);
	}
	this._parent.appendChild(widget._element);
	this._widgets.push(widget);
	/**
	 * 关联元素的删除事件
	 */
	EventOnHandler(widget, "delete", this, "remove");
};

/**
 * 移除控件层中的widget控件
 * @method remove
 * @author JunEnstein 2017-05-19
 * @param  {Widget} widget 需要移除的控件对象
 */
Note.WidgetLayer.prototype.remove = function(widget){
	this._widgets.remove(widget);
	this._parent.removeChild(widget._element);
	labels_index = 1;
	for(var i = 0; i < this._widgets.length; i++){
		if(this._widgets[i]._name == 'Label'){
			this._widgets[i].setId(labels_index++);
		}
	}
};